/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    let head, tail, sumG = 0, sumS = 0

    while (l1 || l2) {
        let a = l1 ? l1.val : 0
        let b = l2 ? l2.val : 0
        sumG = (a + b + sumS) % 10    // 个位

        if (!head) {
            head = tail = new ListNode(sumG)
        } else {
            // 主要理解ListNode结构，把tail的指针往后移然后赋值
            tail.next = new ListNode(sumG)
            tail = tail.next
        }

        sumS = Math.floor((a + b + sumS) / 10)    // 十位

        if (l1) {
            l1 = l1.next
        }
        if (l2) {
            l2 = l2.next
        }
    }
    if (sumS === 1) {
        tail.next = new ListNode(sumS)
    }

    return head
};

function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

let l1 = new ListNode(2)
l1.next = new ListNode(4)
l1.next.next = new ListNode(3)

let l2 = new ListNode(5)
l2.next = new ListNode(6)
l2.next.next = new ListNode(6)